<template>
  <div class="app-container h-flex">
    <div class="app-container__left tree-box">
      <div class="type-title">字典类型</div>
      <ul class="type-list">
        <li
          v-for="item in dicTypeList"
          :key="item.id"
          :class="{ active: item.id === listQuery.dicTypeId }"
          @click="chooseType(item.id)">
          {{ `${item.dtName}（${item.dtCode}）` }}
        </li>
      </ul>
    </div>
    <div
      ref="tree_box_right"
      class="app-container__right h-flex-elastic v-flex overflow-hidden">
      <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm" />
      <div ref="main" class="v-flex-elastic">
        <el-table
          v-if="height>0"
          ref="multipleTable"
          v-loading="listLoading"
          :data="tableData"
          border
          :height="height"
          tooltip-effect="dark"
          style="width: 100%">
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="50" />
          <el-table-column
            prop="dicKey"
            show-overflow-tooltip
            label="字典名称" />
          <el-table-column
            prop="dicValue"
            show-overflow-tooltip
            label="字典值" />
          <el-table-column
            prop="dicDesc"
            show-overflow-tooltip
            label="描述" />
          <el-table-column
            label="启用"
            align="center"
            width="70">
            <template slot-scope="{row,$index}">
              <el-switch v-model="row.status" @change="enable(row,$index)" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="120"
            class-name="small-padding fixed-width">
            <template slot-scope="{row ,$index}">
              <el-button
                v-permission-button="'ITPS-VIEW'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-view"
                @click="view(row)" />
              <el-button
                v-permission-button="'ITPS-UPDATE'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-edit"
                @click="updateForm(row,$index)" />
              <el-button
                v-permission-button="'ITPS-DELETE'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-delete"
                @click="deleteData(row,$index)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-box">
        <pagination
          :total="total"
          :page.sync="listQuery.page"
          :size.sync="listQuery.size"
          @pagination="getList" />
      </div>

      <base-dialog
        class="dictionary-dialog"
        :visible.sync="dialog.visible"
        :title="dialog.title"
        :loading="dialog.loading"
        :disabled="dialog.disabled"
        @open="beforeOpenDialog"
        @updateData="updateData">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          :disabled="dialog.disabled"
          label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="字典名称" prop="dicKey">
                <el-input v-model="temp.dicKey" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="字典值"
                prop="dicValue">
                <el-input v-model="temp.dicValue" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="字典类型" prop="dicTypeId">
                <el-select
                  v-model="temp.dicTypeId"
                  class="filter-item"
                  @change="changeDicType(temp.dicTypeId)">
                  <el-option
                    v-for="item in dicTypeList"
                    :key="item.id"
                    :label="item.dtName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="排序号"
                prop="orderNum">
                <el-input v-model="temp.orderNum" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item
                label="系统描述"
                prop="dicDesc">
                <el-input v-model="temp.dicDesc" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="启用">
                <el-switch v-model="temp.status" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </base-dialog>
      <!-- <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false">

        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="!disabled"
            type="primary"
            @click="dialogStatus==='create'?addData():updateData()">
            保存
          </el-button>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
        </div>
      </el-dialog> -->
    </div>
  </div>
</template>

<script>
import { getType, getList, saveOrUpdate, deleteById } from '@/api/dsc/system/dictionary/general'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscGeneral',
  mixins: [tableMixin],
  data() {
    return {
      value: [],
      dicTypeList: [], // 字典类型list
      treeHeight: 0, // tree高度
      height: 0, // table高度
      tableData: [], // 表格数据
      listQuery: {// 搜索条件
        keyName: '',
        page: 1,
        size: 20,
        dicTypeId: ''// 选中的字典类型id
      },
      filterData: {
        keyName: {
          key: 'keyName',
          type: 'input',
          placeholder: '请输入名称、描述'
        }
      },
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {// 弹窗表单
        id: null,
        dicKey: '',
        dicValue: '',
        dicDesc: '',
        dicTypeId: null,
        dicTypeCode: null,
        status: true
      },
      rowIndex: null,
      rules: {},
      rulesModel: {
        dicKey: [{ required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }],
        dicValue: [{ required: true, message: '必填', trigger: 'blur' },
          { min: 1, message: '大于1个字符', trigger: 'blur' },
          { max: 20, message: '小于20个字符', trigger: 'blur' }],
        dicTypeId: [{ required: true, message: '必选', trigger: 'blur' }],
        orderNum: { pattern: /^\d+$/, message: '请输入正整数', trigger: 'blur' },
        dicDesc: [{ max: 255, message: '小于255个字符', trigger: 'blur' }]
      },
      listLoading: false,
      disabled: false // 是否禁止表单操作
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    getType({}).then((response) => {
      this.dicTypeList = response.data
      if (this.dicTypeList && this.dicTypeList.length > 0) {
        this.listQuery.dicTypeId = this.dicTypeList[0].id
        this.search()
      }
    })
  },
  methods: {
    // 改变dicTypeCode
    changeDicType(id) {
      for (const i of this.dicTypeList) {
        if (id === i.id) {
          this.temp.dicTypeCode = i.dtCode || null
          this.temp.dicTypeAttr = {
            dtTypeId: i.id,
            dtName: i.dtName,
            dtCode: i.dtCode
          }
          return
        }
      }
    },
    // 选择字典类型
    chooseType(id) {
      this.listQuery.dicTypeId = id
      this.listQuery.keyName = ''
      this.search()
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
        for (const i of this.tableData) {
          i.status = !!i.status
        }
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0 * 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 搜索
    search() {
      this.listQuery.page = 1
      this.getList()
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      this.temp.dicTypeId = this.listQuery.dicTypeId
      this.changeDicType(this.temp.dicTypeId)
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.rules = Object.assign({}, this.rulesModel)
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    view(row) {
      // this.disabled = true
      this.temp = Object.assign({}, row) // copy obj
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    updateForm(row, $index) {
      // this.disabled = false
      this.rowIndex = $index
      this.temp = Object.assign({}, row) // copy obj
      this.temp.dicTypeId = this.listQuery.dicTypeId
      // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp, 2)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      const param = Object.assign({}, params)
      param.status = param.status ? 1 : 0
      saveOrUpdate(param).then(response => {
        response.data.status = !!response.data.status
        if (this.dialog.title === '添加') {
          this.tableData.unshift(response.data)
          this.total++
        } else {
          Object.assign(this.tableData[this.rowIndex], response.data)
        }
        this.notifiySuccess('保存成功!')
        this.dialog.visible = false
      })
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 启用、停用
    enable(row, $index) {
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?').then(() => {
        deleteById(row.id).then(response => {
          this.notifiySuccess('删除成功!')
          // this.tableData.splice($index, 1)
          // this.total--
          this.getList()
        })
      }).catch(() => {

      })
    }
  }
}
</script>
